//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['element', 'layer','form','notice', 'admin'], function(){
    var $ = layui.jquery;
    var element = layui.element;
    var layer = layui.layer;
    var form = layui.form;
    var notice = layui.notice;
    var admin = layui.admin;

    var Authorization;//请求接口权限用
    var rcid = '';//区划配置版本
    var row_info="",column_info= "",row_type= "",column_type="";//表格信息配置
    var x="", y= "";//主栏、宾栏
    var tableActiveName= "iden"; //activeName:指标和维度值默认为指标
    var activeName="x";
    var curTarget= {
        node: [],
        type: ""
    };

    var curMeta= admin.getLayerData();  // 获取列表页面传递的数据; 保存综合对象信息及id

    var dataTemp={//模板
        id: undefined,
        version: undefined
    };
    var isCreate=false;
    var matid= ""; //保存综合对象id
    var newtemp = false;//是否新模板
    var tableWidth = 'auto',tableHeight = "";


    var iden={
        //指标信息
        cat_id: "",
        attribute: {
            idenCode: "",
                idenName: ""
        },
        sub: [] //子节点
    };
    var group= {
        //分组信息
        cat_id: "",
        attribute: {
            groupCode: "",
                groupName: ""
        },
        sub: [] //子节点
    };
    var setting={//树设置
        idenSetting:{
            //指标树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeDrag: beforeDrag,
                onDrag: onDrag,
                onExpand: onExpandIdenTree
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
        idenComparsionSetting:{
            //指标对比类型树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeDrag: beforeDrag,
                onDrag: onDrag
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
        groupSetting:{
            //分组树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeDrag: beforeDrag, //用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
                onDrag: onDrag, //用于捕获节点被拖拽的事件回调函数
                onExpand: onExpandGroupTree
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
        regionSetting:{//区划树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeDrag: beforeDrag,
                onDrag: onDrag,
                onExpand: onExpandRegionTree
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
        xysetting: {
            //主栏、宾栏设置
            edit: {
                enable: true,
                showRemoveBtn: true,
                showRenameBtn: false,
                drag: {
                    prev: prevTree,
                    next: nextTree,
                    inner: innerTree
                }
            },
            data: {
                key: {
                    children: "sub"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onRemove: onRemove,
                onMouseUp: onMouseUp
            },
            view: {
                showIcon: true,
                showLine: true
            }
        }
    }

    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getTemplateManagePower();
        init();
    }

    form.on('select(regionSet)', function(data){
        queryRegionTree(data.value);
    });

    //指标和维度面板切换
    element.on('collapse(idenAndGroup)', function(data){
        var type = $(data.title).attr('type');
        if(data.show){
            tableActiveName = $(data.title).attr('type');
        }

    });

    //栏目切换
    element.on('tab(xyTab)', function(data){
        if(data.index == 0){
            activeName = 'x';
        }else{
            activeName = 'y';
        }
    });

    $("#switchTable").click(function () {
        switchTable();
    })
    $("#buildTables").click(function () {
        buildTables();
    })
    $("#saveTemple").click(function () {
        saveTemple();
    })
    $("#deleteTemple").click(function () {
        deleteTemple();
    })
    $("#openTableDialog").click(function () {
        openFullTableDialog();
    });
    function getTemplateManagePower() {
        var str = template("templateManage-tmpl",{});
        document.getElementById("templateManage-tmpl-box").innerHTML = str;
    }
    function init() {
        if(curMeta.dataFormat==1){//分地区数据
            $("#regionTableBox").css('display','block');
            getRegionVersion();
        }
        createIdenTree();
        createIdencomparsion();
        createGroupTree();

        getMacroTemplate(function(arr){
            renderTemplate(arr);
        });

        //初始化树
        $.fn.zTree.init($("#iden"), setting.idenSetting);
        $.fn.zTree.init($("#group"), setting.groupSetting);
        $.fn.zTree.init($("#groupRegion"), setting.regionSetting);
        $.fn.zTree.init($("#x"), setting.xysetting);
        $.fn.zTree.init($("#y"), setting.xysetting);
    }

    // 通过综合对象id查询模板
    function getMacroTemplate(callback){
        axios.get(macroUrl.template.queryTemplate+curMeta.id,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    if(response.data.data!=null){
                        var arr = response.data.data;
                        callback(arr);
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });

    }

    function renderTemplate(arr){
        var datas = strAllReplaceLine(arr);
        column_info = JSON.parse(datas.column_info);
        row_info = JSON.parse(datas.row_info);
        row_type = datas.row_type == 1 ? "iden" : "group";
        column_type = datas.column_type == 1 ? "iden" : "group";
        dataTemp = {
            id: datas.id,
            version: datas.version
        };

        $.fn.zTree.init($("#x"), setting.xysetting, row_info);
        $.fn.zTree.init($("#y"), setting.xysetting, column_info);
        $("#left_div1").html(datas.cross_table);
        $("#right_divx").html(datas.column_table);
        $("#left_div2").html(datas.row_table);
        $("#right_div2").html(datas.data_table);
        tableSize();
        x = row_type;
        y = column_type;
        setTableStyle();
        main.setXyInfo(row_type, column_type);
        bindValue();
    }
    //初始构建指标树
    function createIdenTree() {
        queryIdenAndVal('root',function (datas) {
            $.fn.zTree.init($("#iden"), setting.idenSetting, datas);
        })

    }

    //初始构建指标对比类型树
    function createIdencomparsion() {
        axios.get(macroUrl.iden_comparsion.queryAll,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var datas = [];

                    for(var i = 0; i < arr.length; i++ ){
                        datas[i] = strAllReplaceLine(arr[i]);
                    }
                    for (const row of datas) {
                        row.cat_id = row.id;
                        row.name = row.comparsion_name;
                        row.isParent = false; //此属性用来判断是否能在该节点下添加节点
                        row.attribute = {
                            idenCode: "", //默认为空
                            idencomparsion: row.comparsion_code,
                            idenName: row.comparsion_name,
                            ig_type: "iden", //大类分类：指标、分组
                            Iden_type: "idencomparsion", //标识是指标对比类型
                            path: "",
                            pathName: row.comparsion_name,
                            isPeriod: false
                        };
                        row.sub = []; //存放子节点
                    }
                    $.fn.zTree.init(
                        $("#idencomparsion"),
                        setting.idenComparsionSetting,
                        datas
                    );

                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });

    }

    //初始构建分组树
    function createGroupTree() {
        var req={
            current: 1,
            size: pageSize_noPage,
            name:''
        };
        axios.get(macroUrl.group.queryList,{//第一层请求分组目录
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data.records;
                    var datas = [];

                    for(var i = 0; i < arr.length; i++ ){
                        datas[i] = strAllReplaceLine(arr[i]);
                    }
                    for (const row of datas) {
                        row.cat_id = row.id;
                        row.isParent = true;
                        row.attribute = {
                            isRegionCode: false,
                            groupCode: row.code,
                            groupName: row.name,
                            // level:1,
                            node: 1,
                            isPeriod: false,
                            period: "",
                            ig_type: "group",
                            path: "",
                            pathName: "",
                            idencomparsion: ""
                        };
                        row.sub = []; //存放子节点
                        if (row.data_type == "1") {//分组目录不能拖拽
                            row.drag = true;
                        } else {
                            row.drag = false;
                        }
                    }
                    var treeObj = $.fn.zTree.init($("#group"), setting.groupSetting, datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //查询行政区划树
    function queryRegionTree(value) {
        rcid = value;
        lazyLoadRegionTree();
    }

    //异步请求指标目录或指标
    function queryIdenAndVal(parid,callback) {
        var url = macroUrl.idenAsync.queryIdenAndVal+parid;
        axios.get(url,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var datas = [];
                    for(var i = 0; i < arr.length; i++ ){
                        datas[i] = strAllReplaceLine(arr[i]);
                    }
                    for (const row of datas) {
                        row.cat_id = row.id;
                        row.name = row.iden_name;
                        row.isParent = true;
                        row.attribute = {
                            idenCode: row.iden_code,
                            idenName: row.name,
                            ig_type: "iden",
                            path: "",
                            pathName: "",
                            isPeriod: false,
                            idencomparsion: ""
                        };
                        row.sub = []; //存放子节点
                        if (row.value_type == 1) {
                            row.drag = false;
                        } else {
                            row.drag = true;
                        }
                    }

                    callback(datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //查询区划配置版本
    function getRegionVersion() {
        let req = {
            current:1,
            flag:0,
            size:pageSize_noPage
        }
        axios.get(regionUrl.catalog.catalogList,{
            params:req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var str = template("region-tree-tmpl",arr);
                    document.getElementById("region-tree-box").innerHTML = str;
                    form.render('select')
                    if(arr.total>0){
                        rcid = arr.records[0].id;
                        lazyLoadRegionTree();
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //区划树放在下方懒加载
    function lazyLoadRegionTree(curRegionCode) {
        //查询区划放在下方显示的树
        var code = "";
        if (curRegionCode) {
            code = curRegionCode;
        }
        var req = {
            rcId: rcid,
            regionCode: code,
            regionCodeType: 1
        };
        getRegion(req,function (datas) {
            $.fn.zTree.init($("#groupRegion"), setting.regionSetting, datas);
        })
    }

    //查询区划数据
    function getRegion(req,callback) {
        axios.get(regionUrl.info.queryRegion,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var datas = [];
                    for(var i = 0; i < arr.length; i++ ){
                        datas[i] = strAllReplaceLine(arr[i]);
                    }
                    if (datas.length > 0) {
                        for (const row of datas) {
                            row.cat_id = row.id;
                            row.isParent = true;
                            row.attribute = {
                                isRegionCode: true,
                                groupCode: row.code,
                                groupName: row.name,
                                isPeriod: false,
                                period: "",
                                ig_type: "group",
                                path: "",
                                pathName: "",
                                idencomparsion: ""
                            };
                            row.sub = []; //存放子节点
                            row.drag = true;
                        }
                    }
                    callback(datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //查询下方区划树的下级区划值（懒加载）
    function onExpandRegionTree(event, treeId, treeNode) {
        if(treeNode.sub.length<1) {
            var req = {
                rcId: rcid,
                regionCode: treeNode.code,
                regionCodeType: 1
            };
            getRegion(req, function (datas) {
                const treeObj = $.fn.zTree.getZTreeObj("groupRegion");
                treeObj.addNodes(treeNode, datas);
            });
        }
    }

    //展开指标节点
    function onExpandIdenTree(event, treeId, treeNode) {
        if (treeNode.sub.length > 0) {
            return;
        }else{
            queryIdenAndVal(treeNode.id,function (datas) {
                const treeObj = $.fn.zTree.getZTreeObj("iden");
                treeObj.addNodes(treeNode, datas);
            })
        }

    }

    //展开分组节点
    function onExpandGroupTree(event, treeId, treeNode) {
        if (treeNode.sub.length > 0) {
            return;
        }
        if (treeNode.attribute.node == 1) {
            //如果上级是根目录(分组目录)节点，变请求版本
            var req={
                identid: treeNode.id
            };
            var url = macroUrl.version.queryVersion+treeNode.id;
            axios.get(url,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        for (const row of datas) {
                            row.cat_id = row.id;
                            row.name = row.value;
                            row.isParent = true;
                            row.attribute = {
                                isRegionCode: false,
                                groupCode: row.code,
                                groupName: row.value,
                                isPeriod: false,
                                period: "",
                                //数据管理系统新增
                                vid: row.id,
                                mid: row.identid,
                                memo: row.memo,
                                value: row.value,
                                node: 2,
                                ig_type: "group",
                                path: "",
                                idencomparsion: ""
                            };
                            row.sub = [];
                            row.drag = false;//版本不可拖拽
                        }
                        const treeObj = $.fn.zTree.getZTreeObj("group");
                        treeObj.addNodes(treeNode, datas);
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        } else if (treeNode.attribute.node == 2) {
            //如果上级是版本，请求第一级分组值
            let req = {
                mid: treeNode.attribute.mid,//分组id
                vid: treeNode.attribute.vid,//版本id
                parId: "root"
            };
            getIdentVal(req,function (datas) {
                const treeObj = $.fn.zTree.getZTreeObj("group");
                treeObj.addNodes(treeNode, datas);
            })

        } else {
            //如果上级是分组值，请求下级分组值
            let req = {
                mid: treeNode.attribute.mid,
                vid: treeNode.attribute.vid,
                parId: treeNode.id
            };
            getIdentVal(req,function (datas) {
                const treeObj = $.fn.zTree.getZTreeObj("group");
                treeObj.addNodes(treeNode, datas);
            })
        }
    }

    //请求分组值
    function getIdentVal(req,callback){
        var url = macroUrl.idenval.queryIdenval;
        axios.get(url,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var arr = response.data.data;
                    var datas = [];
                    for(var i = 0; i < arr.length; i++ ){
                        datas[i] = strAllReplaceLine(arr[i]);
                    }
                    for (const row of datas) {
                        row.cat_id = row.id;
                        row.name = row.name;
                        row.isParent = true;
                        row.attribute = {
                            isRegionCode: false,
                            groupCode: row.code,
                            groupName: row.name,
                            isPeriod: false,
                            period: "",
                            //数据管理系统新增
                            id: row.id,
                            vid: row.vid,
                            mid: row.mid,
                            memo: row.memo,
                            value: row.value,
                            node: 3,
                            ig_type: "group",
                            path: "",
                            pathName: "",
                            idencomparsion: ""
                        };
                        row.sub = [];
                        row.drag = false;
                        if (row.data_type == "1") {
                            //不让第一层节店拖拽
                            row.drag = true;
                        } else {
                            row.drag = false;
                        }
                    }
                    callback(datas);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    function beforeDrag(treeId, treeNodes) {
        //拖拽之前
        var answer = isAble2(activeName, treeNodes);
        if (!answer) {
            notice.msg('警告，拖动类型不对！', {icon: 3});
            return answer;
        }
        for (var i = 0, l = treeNodes.length; i < l; i++) {
            if (treeNodes[i].drag === false) {
                return false;
            } else if (
                treeNodes[i].parentTId &&
                treeNodes[i].getParentNode().childDrag === false
            ) {
                return false;
            }
        }
    }
    function onDrag(event, treeId, treeNodes) {
        //拖拽事件
        curTarget.node = treeNodes;
        //新增报告期归入分组
        if (treeId == "groupRegion") {
            curTarget.type = "group";
            return true;
        } else if (treeId == "reportData") {
            curTarget.type = "group";
            return true;
        } else {
            curTarget.type = treeId;
            return true;
        }
    }
    function isnotIdenCompar(treeNodes, targetNode) {
        //检测当该节点为指标类型，目标节点不为指标
        let isnotIden = true;
        if (targetNode != null && targetNode != "null") {
            if (!targetNode.isParent) {
                isnotIden = false;
            }
        }
        if (treeNodes[0].attribute.hasOwnProperty("Iden_type")) {
            //该节点为指标对比类型，判断没有上级目录，指标对比类型不能插入
            if (
                treeNodes[0].attribute.Iden_type == "idencomparsion" &&
                targetNode == null
            ) {
                isnotIden = false;
            }
            //该节点为指标对比类型，目标节点为指标，不可再其前后插入
            if (
                treeNodes[0].attribute.Iden_type == "idencomparsion" &&
                !targetNode.attribute.hasOwnProperty("Iden_type")
            ) {
                isnotIden = false;
            }
        }
        return isnotIden;
    }

    function isLastTree(treeNodes, targetNode) {
        //判断是否是最后一层，如果是，则返回false,不允许插入
        var isinner = true;
        if (targetNode != null && targetNode != "null") {
            if (!targetNode.isParent) {
                isinner = false;
            }
        }
        if (treeNodes[0].attribute.hasOwnProperty("Iden_type")) {
            //判断没有上级目录，指标对比类型不能插入
            if (
                treeNodes[0].attribute.Iden_type == "idencomparsion" &&
                targetNode == null
            ) {
                isinner = false;
            }
        }
        return isinner;
    }

    function isAble(treeId, treeNode) {
        var xTree = $.fn.zTree.getZTreeObj("x");
        var yTree = $.fn.zTree.getZTreeObj("y");
        var xNode = xTree.getNodes();
        var yNode = yTree.getNodes();
        var type = curTarget.type;
        var isSameType = false;
        switch (treeId) {
            case "x":
                if (xNode.length == 0 && yNode.length == 0) {
                    x = type;
                    y = type == "iden" ? "group" : "iden";
                }
                x.indexOf(type) != -1 || type.indexOf(x) != -1
                    ? (isSameType = true)
                    : (isSameType = false);
                break;
            case "y":
                if (xNode.length == 0 && yNode.length == 0) {
                    y = type;
                    x = type == "iden" ? "group" : "iden";
                }
                y.indexOf(type) != -1 || type.indexOf(y) != -1
                    ? (isSameType = true)
                    : (isSameType = false);
                break;
        }
        return isSameType;
    }

    function isAble2(treeId) {
        var xTree = $.fn.zTree.getZTreeObj("x");
        var yTree = $.fn.zTree.getZTreeObj("y");
        var xNode = xTree.getNodes();
        var yNode = yTree.getNodes();
        var type = "";
        switch (tableActiveName) {
            case "iden":
                type = "iden";
                break;
            case "group":
                type = "group";
                break;
            case "region":
                type = "group";
                break;
            case "comparsion":
                type = "iden";
                break;
            default:
                type = "group";
        }
        var isSameType = false;
        switch (treeId) {
            case "x":
                if (xNode.length == 0 && yNode.length == 0) {
                    x = type;
                    y = type == "iden" ? "group" : "iden";
                }
                x.indexOf(type) != -1 || type.indexOf(x) != -1
                    ? (isSameType = true)
                    : (isSameType = false);
                break;
            case "y":
                if (xNode.length == 0 && yNode.length == 0) {
                    y = type;
                    x = type == "iden" ? "group" : "iden";
                }
                y.indexOf(type) != -1 || type.indexOf(y) != -1
                    ? (isSameType = true)
                    : (isSameType = false);
                break;
        }
        return isSameType;
    }

    function onMouseUp(e, treeId, treeNode) {
        var i = isAble(treeId, treeNode);
        // i ? null:alert("类型不对");
        return i;
    }

    function tableSize() {
        const height = document.documentElement.clientHeight - 43 * 4 - 130;
        tableWidth = $("#left_div2").width() + $("#right_div2").width()+2;//预留宽度，防止由边距导致换行
        // tableHeight = height - $("#left_div1").height();
        $(".tableWidth").css("width",tableWidth)
    }

    //设置表格滑动样式
    function setTableStyle() {
        var right_div2 = document.getElementById("right_div2");
        right_div2.onscroll = function() {
            var right_div2_top = scrollTop;
            var right_div2_left = scrollLeft;
            document.getElementById("left_div2").scrollTop = right_div2_top;
            document.getElementById("right_div1").scrollLeft = right_div2_left;
        };
        //设置右边div宽度
        tableSize();
    }

    function bindValue() {
        let input = $("#data_table").find("input");
        $("#data_table")
            .find("input")
            .blur(function() {
                $(this)
                    .siblings("span")
                    .html($(this).val());
            });
        input.bind({
            //paste事件
            paste: function(e) {
                var eve = e.originalEvent;
                var cp = eve.clipboardData;
                var str = null;
                // for IE
                var clipboardData = window.clipboardData;
                // for chrome
                if (!clipboardData) {
                    clipboardData = e.originalEvent.clipboardData;
                }
                str = clipboardData.getData("Text");

                var len = str.split("\n");
                var trStr;
                var columIndex = $(this)
                    .parents("td")
                    .index();
                var rowIndex = $(this)
                    .parents("tr")
                    .index();
                //从excle表格中复制的数据，最后一行为空行，因此无需对len数组中最后的元素进行处理
                for (var i = 0; i < len.length - 1; i++) {
                    //按制表符分割当前行，获取单元格数据
                    trStr = len[i].split(/\t+/);
                    var text = "";
                    for (var j = 0; j <= trStr.length - 1; j++) {
                        text += trStr[j] + "-";
                        //填充数据到table
                        var colum = parseInt(columIndex) + j;
                        var td = $("#data_table").find(
                            'td[rowidx="' +
                            (parseInt(rowIndex) + i) +
                            '"][colidx="' +
                            colum +
                            '"]'
                        );
                        if (td.length == 0) {
                            td = $("#data_table").find(
                                'td[rindex="' +
                                (parseInt(rowIndex) + i) +
                                '"][cindex="' +
                                colum +
                                '"]'
                            );
                        }
                        //var td = $("#data_table").find('td[rowidx="' + (parseInt(rowIndex)+i) + '"][colidx="' + colum + '"]');
                        //var td = $("#data_table").find('td[rindex="' + (parseInt(rowIndex)+i) + '"][cindex="' + colum + '"]');
                        /*var td = $("#data_table").find('td[rindex="' + (parseInt(rowIndex)+i) + '"][colidx="' + colum + '"]');
                          var td = $("#data_table").find('td[rindex="' + (parseInt(rowIndex)+i) + '"][cindex="' + colum + '"]');*/
                        /*var strC = '<input type="text" placeholder="-" value="' + trStr[j] + '"/><span style="display: none;">' + trStr[j] + '</span>';
                          td.html(strC);*/
                        td.find("input").val(trStr[j]);
                        td.find("span").html(trStr[j]);
                    }
                }
                //防止onpaste事件起泡
                return false;
            }
        });
    }

    //清空表
    function clearTable() {
        //先清空四张表的内容
        $("#column_table tbody").html("");
        $("#row_table tbody").html("");
        $("#cross_table tbody").html("");
        $("#data_table tbody").html("");
    }

    //移除后没有值重新初始化树
    function onRemove(treeId, treeNode) {
        let xObj = $.fn.zTree.getZTreeObj("x");
        let xNodes = xObj.getNodes();
        let yObj = $.fn.zTree.getZTreeObj("y");
        let yNodes = yObj.getNodes();
        if(!xNodes){//移除后没有值初始化 zTree
            $.fn.zTree.init($("#x"), setting.xysetting);
        }
        if(!yNodes){
            $.fn.zTree.init($("#y"), setting.xysetting);
        }
        return true;
    }

    function innerTree(treeId, treeNodes, targetNode) {
        if (targetNode != null && targetNode != "null") {
            //上级不为指标对比类型都可以添加子节点
            if (!targetNode.attribute.hasOwnProperty("Iden_type")) {
                targetNode.isParent = true;
            }
        }
        var result = false;
        var i = isAble(treeId, treeNodes);
        var isinner = isLastTree(treeNodes, targetNode);
        i ? null : alert("类型不对！");
        if (i && isinner) {
            result = true;
        }
        return result;
    }

    function nextTree(treeId, treeNodes, targetNode) {
        var result = false;
        var i = isAble(treeId, treeNodes);
        var isinner = isnotIdenCompar(treeNodes, targetNode); //检测当该节点为指标类型，目标节点不为指标
        i ? null : alert("类型不对！");
        if (i && isinner) {
            result = true;
        }
        return result;
    }

    function prevTree(treeId, treeNodes, targetNode) {
        var result = false;
        var i = isAble(treeId, treeNodes);
        var isinner = isnotIdenCompar(treeNodes, targetNode); //检测当该节点为指标类型，目标节点不为指标
        i ? null : alert("类型不对！");
        if (i && isinner) {
            result = true;
        }
        return result;
    }

    //模板转置
    function switchTable() {
        x = x == "iden" ? "group" : "iden";
        y = y == "iden" ? "group" : "iden";
        main.setXyInfo(x, y);
        const xTree = $.fn.zTree.getZTreeObj("x");
        const yTree = $.fn.zTree.getZTreeObj("y");
        const xNode = xTree.getNodes();
        const yNode = yTree.getNodes();
        $.fn.zTree.init($("#x"), setting.xysetting, yNode);
        $.fn.zTree.init($("#y"), setting.xysetting, xNode);
        buildTables(77);
    }

    //生成模板
    function buildTables(m) {
        if (!m) {
            newtemp = true;
        }
        isCreate = true;
        const xTree = $.fn.zTree.getZTreeObj("x");
        const yTree = $.fn.zTree.getZTreeObj("y");
        const xNode = xTree.getNodes();
        const yNode = yTree.getNodes();
        row_info = xNode;
        column_info = yNode;
        row_type = x;
        column_type = y;
        main.setXyInfo(row_type, column_type);
        if(x == "iden" &&xNode.length>0){
            main.createTable(xNode, yNode)
        }else if(y == "iden" &&yNode.length>0){
            main.createTable(yNode, xNode);
        }else{
            notice.msg('必须先选择指标后才能创建模板！', {icon: 3});
            return;
        }

        bindValue();
        setTableStyle();
    }

    //保存模板
    function saveTemple() {
        newtemp = false;
        var rowType = (row_type == "iden") ? 1 : 2;
        var columnType = (column_type == "group") ? 2 : 1;
        //不存在分组时，生成的表格指标都在上面,防止保存建表信息有问题此处判断调整一下,将指标调整到column_table
        //（在支持一维表切换主栏与宾栏时放弃此方法）
        // if (row_type == 1 && (this.column_info && this.column_info.length == 0)) {
        //   row_type = 2;
        //   column_type = 1;
        //   this.row_type = "group";
        //   this.column_type = "iden";
        //   let temp = this.row_info;
        //   this.row_info = this.column_info;
        //   this.column_info = temp;
        // }
        const args = {
            matmid: curMeta.id || matid,
            cross_table: $("#left_div1").html(),
            column_table: $("#right_divx").html(),
            row_table: $("#left_div2").html(),
            data_table: $("#right_div2").html(),
            row_info: JSON.stringify(row_info),
            column_info: JSON.stringify(column_info),
            row_type: rowType,
            column_type: columnType,
            ident_tree: "", //分组树
            iden_tree: "" //指标树
        };
        
        if (!dataTemp.id) {
            //查询没有模板时新增模板
            if (!curMeta.id) {
                notice.msg('请先选择报表！', {icon: 3});
                return;
            }
            if (
                !row_info ||
                !column_info ||
                !row_type ||
                !column_type
            ) {
                notice.msg('请先生成模板！', {icon: 3});
                return;
            } else {
                axios({
                    method: 'POST',
                    url:macroUrl.template.addTemplate,
                    data:$.param(args),
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (response) {
                        if(response.status == 200 &&response.data.message == "success"){
                            isCreate = false;
                            layer.msg("保存成功", {icon: 1});
                            getMacroTemplate(function(arr){
                                dataTemp.id = arr.id;
                                dataTemp.version = arr.version;
                            });
                        }else{
                            layer.msg(response.data.message, {icon: 2});
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    });
            }
        } else {
            //查询有模板时
            args.id = dataTemp.id;
            args.version = dataTemp.version;
            axios({
                method: 'PUT',
                url:macroUrl.template.updateTemplate,
                data:$.param(args),
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        layer.msg("操作成功", {icon: 1});
                    }else{
                        layer.msg(response.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }
    }

    //清空模板
    function deleteTemple(){
        if(dataTemp.id){
            axios({
                method: 'delete',
                url:macroUrl.template.deleteTemplate+ dataTemp.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("操作成功", {icon: 1});
                        isCreate = false;
                        clearTable();
                        $.fn.zTree.init($("#x"), setting.xysetting);
                        $.fn.zTree.init($("#y"), setting.xysetting);
                        dataTemp.id = undefined;
                        dataTemp.version = undefined;
                        row_info="";
                        column_info= "";
                        row_type= "";
                        column_type="";
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        }else{//清空页面上的遗留数据
            notice.msg('还没有模板可供删除！', {icon: 3});
            isCreate = false;
            clearTable();
            $.fn.zTree.init($("#x"), setting.xysetting);
            $.fn.zTree.init($("#y"), setting.xysetting);
            dataTemp.id = undefined;
            dataTemp.version = undefined;
            row_info="";
            column_info= "";
            row_type= "";
            column_type="";
        }
    }

    //全屏表格显示
    function openFullTableDialog(){
        admin.open({
            type: 1,
            title: '表格模板', //不显示标题栏
            content: $(".templatetablecontent").html(),
            offset: 'rt',
            area:['100vw;','100vh'],
            id:"fullTableDialog",
            end: function () {
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
});

